package com.jdcjk.project.car.view;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.jdcjk.Constant;
import com.jdcjk.R;
import com.jdcjk.UrlAddress;
import com.jdcjk.base.presenter.BasePresenter;
import com.jdcjk.base.view.BaseFragment;
import com.jdcjk.project.account.model.entity.Result;
import com.jdcjk.project.car.model.entity.TerminalInfoListResult;
import com.jdcjk.project.car.presenter.CarPresenter;
import com.jdcjk.project.car.view.baidu.BDMapCarWarningDialog;
import com.jdcjk.project.car.view.gaode.GDMapCarWarningDialog;
import com.jdcjk.project.main.model.adapter.WarningInfoAdapter;
import com.jdcjk.project.main.model.entity.CarWarningInfo;
import com.jdcjk.util.PreferencesUtils;
import com.jdcjk.util.TerminalWarmingJudge;
import com.jdcjk.view.LoadingDialog;
import com.jdcjk.view.RefreshLayout;
import com.mcxtzhang.swipemenulib.SwipeMenuLayout;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Request;

/**
 * Created by dong on 2016/12/13.
 * 报警信息
 */
public class CarWarmingInfoFragment extends BaseFragment<CarPresenter> {
    private final String TAG = CarWarmingInfoFragment.class.getSimpleName();
    private CarPresenter carPresenter;
    //总的报警信息列表
    private List<CarWarningInfo> carWarningInfoList;
    //显示的报警信息列表（防止一次显示过多数据）
    private List<CarWarningInfo> showCarWarningInfoList;
    //支持上拉下拉刷新的布局
    private RefreshLayout carWarming_refreshlayout;
    //顶栏标题textView
    private TextView barTitle_textview;
    private RelativeLayout withoutCarWarming_relativerLayout;
    private ListView carWarming_listView;
    private CarWarmingFragmentAdapter adapter;
    private int terminalId;
    //加载弹窗
    private LoadingDialog loadingDialog;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_car_warning;
    }

    @Override
    public CarPresenter bindPresenter() {
        carPresenter = new CarPresenter(getContext());
        return carPresenter;
    }

    @Override
    public void initContentView(View viewContent) {
        //顶栏返回button设置监听
        viewContent.findViewById(R.id.back_btn).setOnClickListener(this);
        barTitle_textview = (TextView) viewContent.findViewById(R.id.bar_title_textview);
        barTitle_textview.setText(R.string.car_warming_info);
        viewContent.findViewById(R.id.back_btn).setOnClickListener(this);
        withoutCarWarming_relativerLayout = (RelativeLayout) viewContent.findViewById(R.id.fragment_car_warming_without_car_warming);
        carWarming_listView = (ListView) viewContent.findViewById(R.id.fragment_car_warming_lv);
        carWarming_refreshlayout = (RefreshLayout) viewContent.findViewById(R.id.fragment_car_warming_refreshlayout);
        //初始化加载dialog
        loadingDialog = new LoadingDialog(getActivity(), R.style.dialogTheme);
        //设置下拉刷新
        swipeRefreshLayoutSet();
    }


    @Override
    public void initData() {
        Bundle bundle = getArguments();//从activity传过来的Bundle
        //获取设备Id
        terminalId = bundle.getInt(Constant.TerminalInfo.terminalId);
        // 获取数据
        presenter.getCarWarmingInfo(UrlAddress.GET_SOS_LOCATION, String.valueOf(terminalId), new BasePresenter.OnUIThreadListener<TerminalInfoListResult>() {
            @Override
            public void onBefore(Request request, int id) {
                loadingDialog.show();
                loadingDialog.setTextView(R.string.is_loading);
            }

            @Override
            public void onAfter(int id) {

            }

            @Override
            public void onError(Call call, Exception e, int i) {
                loadingDialog.dismiss();
                Toast.makeText(getActivity(), R.string.system_exception, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(TerminalInfoListResult terminalInfoListResult) {
                switch (terminalInfoListResult.getStatus()) {
                    case "OK":
                        carWarningInfoList = TerminalWarmingJudge.addWamingName(terminalInfoListResult.getResult());
                        //判断报警信息量,若大于20则分页显示
                        if (carWarningInfoList.size() > 20) {
                            showCarWarningInfoList = new ArrayList<>();
                            showCarWarningInfoList.addAll(carWarningInfoList.subList(0, 20));
                            adapter = new CarWarmingFragmentAdapter(getActivity(), showCarWarningInfoList);
                        } else {
                            adapter = new CarWarmingFragmentAdapter(getActivity(), carWarningInfoList);
                        }
                        carWarming_listView.setAdapter(adapter);
                        refreshUI(carWarningInfoList);
                        clearUnReadInfo();
                        break;
                    case "FAILED":
                        Toast.makeText(getActivity(), terminalInfoListResult.getMessage(), Toast.LENGTH_SHORT).show();
                        break;
                }
                loadingDialog.dismiss();
            }
        });

        //清除下拉刷新加载
        carWarming_refreshlayout.setRefreshing(false);
    }


    private void swipeRefreshLayoutSet() {
        carWarming_refreshlayout.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_blue_light, android.R.color.holo_orange_light, android.R.color.holo_green_light);
        // 下拉刷新
        carWarming_refreshlayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        initData();
                    }
                }, 400);
            }
        });
        // 上拉刷新
        carWarming_refreshlayout.setOnLoadListener(new RefreshLayout.OnLoadListener() {
            @Override
            public void onLoad() {
                carWarming_refreshlayout.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        if (showCarWarningInfoList.size() != carWarningInfoList.size()) {
                            //如果数据大于显示数据的一倍，则添加之后的二十条数据
                            if (showCarWarningInfoList.size() + 20 < carWarningInfoList.size()) {
                                showCarWarningInfoList.addAll(carWarningInfoList.subList(showCarWarningInfoList.size(), showCarWarningInfoList.size() + 20));
                            } else if (showCarWarningInfoList.size() + 20 > carWarningInfoList.size()) {
                                showCarWarningInfoList.addAll(carWarningInfoList.subList(showCarWarningInfoList.size(), carWarningInfoList.size()));
                            }
                        } else {
                            //如果列表数据数量相等，则说明没有更多数据
                            Toast.makeText(getActivity(), R.string.no_more_warning_info, Toast.LENGTH_SHORT).show();
                        }
                        adapter.notifyDataSetChanged();
                        carWarming_refreshlayout.setLoading(false);
                        carWarming_refreshlayout.removeFootView();
                    }
                }, 1500);

            }
        });
    }

    /**
     * 删除报警信息
     *
     * @param warningInfoId 信息id
     * @param position      报警信息在报警信息列表中的位置
     */
    private void deleteWarningInfo(String warningInfoId, final int position) {
        carPresenter.deleteWarningInfo(UrlAddress.DELETE_LOCATION, warningInfoId, new BasePresenter.OnUIThreadListener<Result>() {
            @Override
            public void onBefore(Request request, int id) {

            }

            @Override
            public void onAfter(int id) {

            }

            @Override
            public void onError(Call call, Exception e, int i) {
                Toast.makeText(getActivity(), R.string.system_exception, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(Result result) {
                switch (result.getStatus()) {
                    case "OK":
                        Toast.makeText(getActivity(), result.getMessage(), Toast.LENGTH_SHORT).show();
                        //删除当前界面的该条信息，并刷新界面
                        carWarningInfoList.remove(position);
                        adapter.removeItem(position);
                        refreshUI(showCarWarningInfoList);
                        break;
                    case "FAILED":
                        Toast.makeText(getActivity(), result.getMessage(), Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });
    }

    /**
     * 将所有未阅读的报警信息改为已阅读
     */
    public void clearUnReadInfo() {
        carPresenter.updateMsgStatus(UrlAddress.UPDATA_MSG_STATUS, String.valueOf(terminalId), new BasePresenter.OnUIThreadListener<Result>() {
            @Override
            public void onBefore(Request request, int id) {

            }

            @Override
            public void onAfter(int id) {

            }

            @Override
            public void onError(Call call, Exception e, int i) {

            }

            @Override
            public void onResponse(Result result) {
            }
        });
    }

    private void refreshUI(List<CarWarningInfo> carWarningInfoList) {
        if (carWarningInfoList != null && carWarningInfoList.size() > 0) {
            withoutCarWarming_relativerLayout.setVisibility(View.GONE);
            carWarming_listView.setVisibility(View.VISIBLE);
        } else {
            withoutCarWarming_relativerLayout.setVisibility(View.VISIBLE);
            carWarming_listView.setVisibility(View.GONE);
        }
    }

    class CarWarmingFragmentAdapter extends BaseAdapter {
        private Context context;
        private List<CarWarningInfo> dataList;

        public CarWarmingFragmentAdapter(Context context, List<CarWarningInfo> dataList) {
            this.context = context;
            this.dataList = dataList;
        }

        @Override
        public int getCount() {
            return dataList.size();
        }

        @Override
        public CarWarningInfo getItem(int i) {
            return dataList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(final int i, View view, ViewGroup viewGroup) {
            final ViewHolder viewHolder;
            final CarWarningInfo carWarningInfo = dataList.get(i);
            if (view == null) {
                viewHolder = new ViewHolder();
                view = getActivity().getLayoutInflater().inflate(R.layout.adapter_car_warming, null);
                viewHolder.carName_textView = (TextView) view.findViewById(R.id.fragment_car_warming_car_name);
                viewHolder.carWarningInfo_textView = (TextView) view.findViewById(R.id.fragment_car_warning_info_tv);
                viewHolder.warningInfo_spinner = (Spinner) view.findViewById(R.id.fragment_car_warning_info_spinner);
                viewHolder.locateTime_textView = (TextView) view.findViewById(R.id.fragment_car_warning_locate_time);
                viewHolder.warmingTime_textView = (TextView) view.findViewById(R.id.fragment_car_warning_time);
                viewHolder.warmingSpeed_textView = (TextView) view.findViewById(R.id.fragment_car_warning_speed);
                viewHolder.itemDelete_button = (ImageButton) view.findViewById(R.id.item_delete_btn);
                viewHolder.carWarning_relativeLayout = (RelativeLayout) view.findViewById(R.id.car_warning_rl);
                viewHolder.swipeMenu_layout = (SwipeMenuLayout) view.findViewById(R.id.swipe_menu_layout);
                view.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) view.getTag();
            }
            // 设置车辆名称
            viewHolder.carName_textView.setText(carWarningInfo.getDisplayid());
            // 设置定位时间
            viewHolder.locateTime_textView.setText(carWarningInfo.getLocationTime());
            // 设置报警时间
            viewHolder.warmingTime_textView.setText(carWarningInfo.getUpdateTime());
            //设置车速
            viewHolder.warmingSpeed_textView.setText(String.valueOf(carWarningInfo.getSpeed()) + "km/h");
            //判断报警数据量，若只有一条则采用textview显示，否则采用spinner显示
            if (carWarningInfo.getWarningList().size() == 1) {
                viewHolder.carWarningInfo_textView.setVisibility(View.VISIBLE);
                viewHolder.carWarningInfo_textView.setText(carWarningInfo.getWarningList().get(0));
                //不显示spinner
                viewHolder.warningInfo_spinner.setVisibility(View.GONE);
            } else if (carWarningInfo.getWarningList().size() > 1) {
                //不显示textview
                viewHolder.carWarningInfo_textView.setVisibility(View.GONE);
                viewHolder.warningInfo_spinner.setVisibility(View.VISIBLE);
                // 设置报警列表数据
                WarningInfoAdapter adapter = new WarningInfoAdapter(context, carWarningInfo.getWarningList());
                //加载适配器
                viewHolder.warningInfo_spinner.setAdapter(adapter);
            }
            //侧滑出的删除按钮监听
            viewHolder.itemDelete_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //删除该条报警信息
                    deleteWarningInfo(String.valueOf(carWarningInfo.getId()), i);
                    viewHolder.swipeMenu_layout.quickClose();
                }
            });
            //报警列表信息Item监听
            viewHolder.carWarning_relativeLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //获得所设置的地图类型
                    String mapType = PreferencesUtils.getString(getActivity(), PreferencesUtils.MAP_TYPE);
                    CarWarningInfo carWarningInfo = carWarningInfoList.get(i);
                    if (mapType.equals("BaiDu")) {
                        BDMapCarWarningDialog bdMapCarWarningDialog = new BDMapCarWarningDialog();
                        bdMapCarWarningDialog.setCarWarningInfo(carWarningInfo);
                        bdMapCarWarningDialog.show(getActivity().getSupportFragmentManager(), "");
                    } else {
                        GDMapCarWarningDialog GDMapCarWarningDialog = new GDMapCarWarningDialog();
                        GDMapCarWarningDialog.setCarWarningInfo(carWarningInfo);
                        GDMapCarWarningDialog.show(getActivity().getSupportFragmentManager(), "");
                    }
                }
            });
            return view;
        }


        public void removeItem(int position) {
            dataList.remove(position);
            notifyDataSetChanged();
        }
    }

    class ViewHolder {
        TextView carName_textView;
        TextView carWarningInfo_textView;
        Spinner warningInfo_spinner;
        TextView locateTime_textView;
        TextView warmingTime_textView;
        TextView warmingSpeed_textView;
        ImageButton itemDelete_button;
        RelativeLayout carWarning_relativeLayout;
        SwipeMenuLayout swipeMenu_layout;
    }
}
